from functools import reduce
import json
import sys
from pathlib import Path
sys_path = str(Path(__file__).resolve().parent.parent)
sys.path.append(sys_path)

from ai_configs import defalut_ai_config
from main import ai_chat_history

MAX_LEN = 5
histories = []

# /*---------------------------------------定义工具类-------------------------------------------*/
class AgentTool:
  def __init__(self,name,description,invoke):
    self.name = name
    self.description = description
    self.invoke = invoke
  
# /*---------------------------------------实例大模型架构工具类-------------------------------------------*/
def architect_invoke():
  with open("./data/architect.json","r",encoding="utf-8") as file:
    content = file.read()
    return content
  
architect_tool = AgentTool(
  name="architect",
  description="查询大模型架构",
  invoke=architect_invoke
)

# /*---------------------------------------实例大模型历史工具类-------------------------------------------*/
def history_invoke():
  with open("./data/history.json","r",encoding="utf-8") as file:
    content = file.read()
    return content
  
history_tool = AgentTool(
  name="history",
  description="查询大模型历史",
  invoke=history_invoke
)

tools = [architect_tool,history_tool]

TOOL_PROMPT = reduce(lambda x,y:x+f"  {y.name}\n  工具作用：{y.description}\n",tools,"")
# print(TOOL_PROMPT)

SYS_PROMPT = '''
你是一名工具调用专家，需要根据用户的提问找出需要调用的工具返回给用户，返回的格式为一个json，json格式为{result_params}，你要把找到的工具名赋值给tool属性

工具列表清单：
{tools_params}
'''.format(
  result_params="""{"tool":""}""",
  tools_params=TOOL_PROMPT
)
# print(SYS_PROMPT)

def get_user_content():
  user_content = input("你好，请输入你的问题：")
  return user_content

global_user_content = get_user_content()

while global_user_content!="exit":
  histories.append({
    "role":"user",
    "content":global_user_content
  })
  current_histories = histories[-1*MAX_LEN:]
  current_histories.insert(0,{
    "role":"system",
    "content":SYS_PROMPT
  })

  try:
    tool_info = ai_chat_history(current_histories,defalut_ai_config["doubao"])
    print(tool_info,"tool_info 1")
    tool_info = json.loads(tool_info)
    tool_data = None
    for tool in tools:
      if tool.name == tool_info["tool"]:
        tool_data = tool.invoke()

    print(tool_data,"tool_data")
    histories.append({
      "role":"assistant",
      "content":tool_data
    })
    current_histories = histories[-1*MAX_LEN:]
    current_histories.insert(0,{
      "role":"system",
      "content":"你需要根据工具的返回结果和用户的提问，整理成通俗易懂的文本来回答用户"
    })
    tool_info = ai_chat_history(current_histories,defalut_ai_config["doubao"])
    print(tool_info,"tool_info 2")
    histories.append({
     "role":"assistant",
      "content":tool_info
    })
  except Exception as e:
    print(f"发生错误，具体信息如下：{e}")
  global_user_content = get_user_content()
